package org.hbkj.springbootmybatis.controller;

import org.hbkj.springbootmybatis.entity.UserDo;
import org.hbkj.springbootmybatis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    // 原有CRUD接口保持不变
    @GetMapping
    public List<UserDo> selectAll() {
        return userService.selectAll();
    }

    @GetMapping("/{id}")
    public UserDo selectOne(@PathVariable Long id) {
        return userService.selectOne(id);
    }

    @PostMapping
    public int insert(@RequestBody UserDo userDo) {
        return userService.insert(userDo);
    }

    @PutMapping("/{id}")
    public int update(@PathVariable Long id, @RequestBody UserDo userDo) {
        userDo.setId(id);
        return userService.update(userDo);
    }

    @DeleteMapping("/{id}")
    public int delete(@PathVariable Long id) {
        return userService.delete(id);
    }

    // 新增：手机号唯一性检查接口（供前端注册时验证）
    @GetMapping("/checkPhone")
    public Map<String, Boolean> checkPhone(@RequestParam String phone) {
        boolean exists = userService.findByPhone(phone) != null;
        return Collections.singletonMap("exists", exists);
    }

    // 核心修改：登录接口改为手机号+密码验证
    @PostMapping("/login")
    public UserDo login(@RequestBody Map<String, String> loginInfo) {
        // 1. 从请求参数中获取手机号和密码（与前端保持一致）
        String phone = loginInfo.get("phone");
        String password = loginInfo.get("password");

        // 2. 调用Service层通过手机号查询用户
        UserDo user = userService.findByPhone(phone);

        // 3. 验证用户是否存在及密码是否正确
        if (user == null) {
            throw new RuntimeException("手机号未注册");
        }
        if (!password.equals(user.getPassword())) { // 明文验证（生产环境需加密）
            throw new RuntimeException("密码错误");
        }

        // 4. 登录成功，返回用户信息（建议脱敏，如隐藏密码）
        user.setPassword(null); // 清除返回结果中的密码，增强安全性
        return user;
    }
}